<template>
  <div class="page">
    <v-pageTitle title="角色管理"></v-pageTitle>
    <v-pageHeader>
        <el-button size="small" type="primary" icon="el-icon-circle-plus" v-if="hasPermission('新增')" @click="batchAdd">新增</el-button>
    </v-pageHeader>

    <imp-panel>
      <v-pageSearch v-if="hasPermission('查询')">
        <el-form :inline="true" :model="formSearch" class="demo-form-inline">
          <el-form-item label="角色名称" prop="roleName">
            <el-select style="width:100%;" size="small" v-model="formSearch.roleName" clearable filterable placeholder="请选择">
              <el-option
                v-for="item in role_options"
                :key="item.nameZh"
                :label="item.nameZh"
                :value="item.nameZh">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="角色名称">
            <el-input v-model="formSearch.roleName" size="small" placeholder=""></el-input>
          </el-form-item> -->
          <el-form-item>
            <el-button size="small" type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </v-pageSearch>
    
      <el-table size="small" v-loading="table.loading"  
        @row-click="rowClick" 
        :max-height="table.autoHeight"
        :data="table.body" @selection-change="selsChange" 
        :header-row-style='headerBg' :header-cell-style="headerBg"
        :default-sort="{prop: 'date', order: 'descending'}">
          <el-table-column prop="name" label="角色代码" min-width="120" sortable>
          </el-table-column>
          <el-table-column prop="nameZh" label="角色名称" min-width="120" sortable>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="100" sortable>
          </el-table-column>
          <el-table-column prop="createName" label="创建人" min-width="120" sortable>
          </el-table-column>
          <el-table-column prop="createTime" label="创建日期" min-width="100" sortable>
            <template slot-scope="scope">
              {{getName_date(scope.row.createTime)}}
            </template>
          </el-table-column>
          <el-table-column prop="modifyName" label="最后修改人" min-width="120" sortable>
          </el-table-column>
          <el-table-column prop="modifyTime" label="最后修改日期" min-width="120" sortable>
            <template slot-scope="scope">
              {{getName_date(scope.row.modifyTime)}}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="260">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="default"
                icon="edit"
                v-if="hasPermission('编辑')"
                @click="batchEdit(scope.row)">编辑
              </el-button>
              <el-button
                size="mini"
                type="info"
                icon="el-icon-setting"
                v-if="hasPermission('配置权限')"
                @click="handleRoleConfig(scope.$index, scope.row)">配置权限
              </el-button>
              <el-button
                size="mini"
                type="danger"
                v-if="hasPermission('删除')"
                @click="handleDel(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
      </el-table>
    </imp-panel>

    <!--编辑角色信息界面-->
    <el-dialog title="角色信息" :visible.sync="editFormVisible1" @close="dialogClose1('ruleForm1')" :close-on-click-modal="false">
      <el-form :model="ruleForm1" :rules="rules1" ref="ruleForm1" label-width="160px" size="mini">
        <el-form-item label="角色代码" prop="name">
          <el-input type="text" v-model="ruleForm1.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="nameZh">
          <el-input type="text" v-model="ruleForm1.nameZh" @blur="nameBlur(ruleForm1.nameZh)" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :rows="2"
            placeholder=""
            v-model="ruleForm1.remark">
          </el-input>
        </el-form-item>
        <el-form-item>
            <el-button  type="primary" @click.native="submitForm1('ruleForm1')" :loading="editLoading1">提交</el-button>
            <el-button @click="resetForm1('ruleForm1')">重置</el-button>
            <el-button  @click.native="editFormVisible1 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--编辑权限信息界面-->
    <el-dialog title="权限信息" :visible.sync="editFormVisible2" :top=top @close="dialogClose2('ruleForm2')" :close-on-click-modal="false">
      <el-form :model="ruleForm2" :rules="rules2" ref="ruleForm2" label-width="80px" size="mini">
        <!--<el-form-item label="">
          <el-input
            style="width:50%"
            size="small"
            placeholder="输入关键字进行过滤"
            v-model="filterText">
          </el-input>
        </el-form-item>-->
        <el-form-item label="" prop="treeData">
          <el-tree
            :data="ruleForm2.treeData"
            show-checkbox
            default-expand-all
            :highlight-current='treeCurrent'
            node-key="id"
            ref="tree"
            :filter-node-method="filterNode"
            :props="ruleForm2.defaultProps">
          </el-tree>
        </el-form-item>
        <el-form-item>
          <el-button  type="primary" @click.native="submitForm2('ruleForm2')" :loading="editLoading2">提交</el-button>
          <el-button @click="resetForm2('ruleForm2')">重置</el-button>
          <el-button  @click.native="editFormVisible2 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import panel from "@/components/common/panel.vue"
import util from '@/util/util'
  export default {
    components: {
      'imp-panel': panel
    },
    data() {
      return {
        top: '2vh',
        formSearch:{
          roleName: '',
          menuName: ''
        },

        table: {
            loading: true,
            autoHeight: 634,
            body: []
        },
        sels:[],
        role_options:[],  //角色列表
        
        isAdd: true,
        ruleForm1: {
          name: '',
          nameZh: '',
          remark: ''
        },
        rules1: {
          name: [
            { required: true, message: '请输入角色代码', trigger: 'blur' },
            // { min: 1, max: 4, message: '长度在 1 到 4 个字符', trigger: 'blur' }
          ],
          nameZh: [
            { required: true, message: '请输入角色名称', trigger: 'blur' } 
          ]
        },

        filterText: '',
        treeCurrent: false,
        currentRow: {},
        ruleForm2: {
          //角色菜单权限树结构数据
          treeData: [],
          defaultProps: {
            children: 'children',
            label: 'name'
          }
        },
        rules2: {},
        
        editFormVisible1: false,//编辑界面是否显示
        editFormVisible2: false,//编辑界面是否显示
        editLoading1: false,
        editLoading2: false,
      }
    },
    methods: {
      //字典数据获取
      baseInfo(){
        let this_ = this;
        // 菜单数据获取
        util.httpJesen('/base/basic/baseMenuTree',6,function(data){
          function dealWithData(json){
            for(var i = 0; i<json.length; i++){
              if(json[i].requireAuth === false){
                json = json.splice(i,1);
              }
              if(json[i].children!== undefined){
                dealWithData(json[i].children)
              }
            }
            return json;
          };
          this_.ruleForm2.treeData = dealWithData(data.data.baseMenus);
        });

        // 获取角色
        let roles_params = {
          "nameZh":"",
          "menuName":""
        };
        util.httpJesen('base/basic/allBaseRoles',roles_params,function(data){
          //data.data.unshift({id:'',nameZh:'全部'})
          this_.role_options = data.data;
        });

      },
      headerBg: function(row){
        return { "background": "#EEF1F6","color":"#1F2D3D" };
      },
      onSearch(){
        this.getTableData()
      },
      getTableData(val,flag) {
        // ajax 查询表格数据
        let this_ = this;
        this_.table.loading = true;
        //let url = 'base/basic/allBaseRoles';
        let url = 'base/basic/allBaseRoles';
        
        let params = {
          "nameZh":this.formSearch.roleName,
          "menuName":this.formSearch.menuName
        };

        util.httpJesen(url,params,function(data){
            this_.table.body = data.data;
            this_.table.loading = false;
            this_.editFormVisible1 = false;
            this_.editFormVisible2 = false;
        });
      },
      //行选取事件
      selsChange: function (sels) {
        console.log(sels)
				this.sels = sels;
			},
      //日期处理
      getName_date(date){
        if(date){
          return util.formatDate.format(new Date(date), 'yyyy-MM-dd')
        }
      },
      // 行点击事件
      rowClick(row) {
        console.log(row.name)
      },
      //显示新增界面
      batchAdd(){
        this.editFormVisible1 = true;
        this.isAdd = true;
      },
      //显示编辑界面
			batchEdit: function (row) {
				this.editFormVisible1 = true;
        this.isAdd = false;
				this.ruleForm1 = Object.assign({}, row);
			},
      // 显示权限配置页面
      handleRoleConfig: function(index,row){
        this.editFormVisible2 = true;
        this.currentRow = Object.assign({}, row);
        let this_ = this;
        // 菜单数据获取
        util.httpJesen('/base/basic/baseMenuTree',this_.currentRow.id,function(data){
          let mids = data.data.mids;
          console.log(mids.filter(x => x>=15))
          let arr = mids.filter(x => x>=15);
          this_.$refs.tree.setCheckedKeys(arr);
        });
      },
      //close 关闭的回调
      dialogClose1(formName){
        this.resetForm1(formName)
      },
      dialogClose2(formName){
        this.resetForm2(formName)
      },
      submitForm1(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let this_ = this;
            this_.editLoading1 = true;
            let params = Object.assign({}, this_.ruleForm1);
            delete params['pageSize'];
            delete params['page'];
    
            let url = this_.isAdd ? 'base/basic/addNewBaseRole' : 'base/basic/updateBaseRole';
            util.httpJesen(url,params,function(data){
              this_.editFormVisible1 = false;
              this_.getTableData();
              this_.baseInfo();
            });
            setTimeout(function(){
              this_.editLoading1 = false;
            },2000);
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      submitForm2(formName) {
        let mids = this.$refs.tree.getCheckedKeys();
        let this_ = this;
        this_.editLoading2 = true;
        
        let params = {
          id: this.currentRow.id,
          mids: mids
        }

        // let url = this_.isAdd ? 'base/basic/addNewBaseMenuRole' : 'base/basic/updateBaseMenuRole';
        let url = 'base/basic/updateBaseMenuRole';
        console.log(params)
        util.httpJesen(url,params,function(data){
          this_.getTableData()
          this_.editFormVisible2 = false;
        });
        setTimeout(function(){
          this_.editLoading2 = false;
        },2000);
      },
      // 获取拼音
      nameBlur(name){
        console.log(name)
      },
      // 重置
      resetForm1(formName) {
        this.$refs[formName].resetFields();
        this.ruleForm1 = {
          name: '',
          nameZh: '',
          remark: ''
        }
      },
      // 过滤tree
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      //清空tree
      resetForm2(formName) {
        this.$refs.tree.setCheckedKeys([]);
      },
      //删除
			handleDel: function (index, row) {
        let this_ = this;
				this.$confirm('确认删除该角色吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this_.table.loading = true;
          let url = 'base/basic/deleteBaseRole';
          util.httpJesen(url,row.id,function(data){
            this_.getTableData();
            this_.table.loading = false;
            this_.$message({
              message: '删除成功',
              type: 'success'
						});
          });
				}).catch(() => {

				});
			}
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    mounted() {
      // 获取table数据
      this.getTableData();
      this.baseInfo();

      //监控浏览器高度 设置table最大高度
      let this_ = this;
      let clientHeight = document.body.clientHeight; 
      this_.table.autoHeight = clientHeight-260;
      window.addEventListener('resize', function(){
        let clientHeight = document.body.clientHeight; 
        this_.table.autoHeight = clientHeight-2860;
      })
    },
    beforeDestory(){
    }
  }
</script>